import React, { FC, useState, useEffect, useRef, useCallback } from 'react';
import { SearchBar, WingBlank } from 'antd-mobile';
import { useLocation, Location, history } from 'umi';
import { useObserverHook, useImgHooks } from '@/hooks';
import { Empty, LoadMore } from '@/components';
import { IPageProps, IHouseItemProps } from '@/interface';
import { fetchHouseList } from '@/api/search';
import { LOAD_MORE_ID, PAGE_PARAMS } from '@/emuns';
import { SearchSkeletons } from '@/skeletons';

import './index.less';

const Search: FC = () => {
  const { query }: Location = useLocation();
  const [houseName, setHouseName] = useState('');
  const [page, setPage] = useState<IPageProps>(PAGE_PARAMS);
  const [houseList, setHouseList] = useState<IHouseItemProps[]>([]);
  const [showLoading, setShowLoading] = useState(true);
  const [showSkeletons, setShowSkeletons] = useState(true);
  const searchRef = useRef<any>(null);
  const [houseVal, setHouseVal] = useState('');
  const { code, startTime, endTime } = query as any;

  const [houses, loading] = fetchHouseList(
    {
      ...page,
      houseName,
      code: code[0],
      startTime: startTime && startTime + ' 00:00:00',
      endTime: endTime && endTime + ' 23:59:59',
    },
    [page.pageNum, houseVal],
  );

  useEffect(() => {
    return () => {
      setPage(PAGE_PARAMS);
      setHouseList([]);
    };
  }, [setPage, setHouseList]);

  useEffect(() => {
    if (!loading && Array.isArray(houses)) {
      if (houses.length) {
        setHouseList(() => [...houseList, ...houses]);
        if (houses.length < page.pageSize) {
          setShowLoading(false);
        }
      } else {
        setShowLoading(false);
      }
    }
  }, [houses]);

  /**
   * 搜索框获取焦点
   */
  useEffect(() => {
    searchRef.current && searchRef.current.focus();
  }, [searchRef.current]);

  const handleChange = useCallback((val: string) => {
    setHouseName(val);
  }, []);
  const _submit = useCallback(
    (val: string) => {
      if (val !== houseVal) {
        setHouseVal(val);
        setPage(() => ({
          ...page,
          pageNum: 1,
        }));
        setHouseList([]);
      }
    },
    [houseVal, setHouseVal, setPage, setHouseList],
  );
  const handleCancel = useCallback(() => {
    setHouseName('');
    _submit('');
  }, [setHouseName, _submit]);
  const handleSubmit = useCallback(
    (val: string) => {
      setHouseList([]);
      _submit(val);
    },
    [_submit, setHouseList],
  );

  useObserverHook('#' + LOAD_MORE_ID, entries => {
    if (!loading && entries[0].isIntersecting) {
      setPage(() => ({
        ...page,
        pageNum: page.pageNum + 1,
      }));
    }
  });

  useImgHooks('.item-img');

  const handleItemClick = useCallback((id: string | number) => {
    history.push({
      pathname: '/house',
      query: {
        id,
      },
    });
  }, []);

  useEffect(() => {
    if (!loading && showSkeletons) {
      setShowSkeletons(false);
    }
  }, [loading]);

  return (
    <div className="search-page-wrap">
      <SearchBar
        ref={searchRef}
        placeholder="搜索民宿"
        value={houseName}
        onChange={handleChange}
        onCancel={handleCancel}
        onSubmit={handleSubmit}
      />
      <div className="search-lists">
        {showSkeletons ? (
          <SearchSkeletons />
        ) : !houseList.length ? (
          <Empty />
        ) : (
          <WingBlank size="md">
            {houseList.map((item, index) => (
              <div
                className="item"
                key={`${item.id}${index}`}
                onClick={() => handleItemClick(item.id)}
              >
                <img
                  alt="img"
                  className="item-img"
                  src={require('../../assets/defaultImg.png')}
                  data-src={item.imgs[0]?.url}
                />
                <div className="item-right">
                  <div className="title">{item.name}</div>
                  <div className="price">￥{item.price}</div>
                </div>
              </div>
            ))}
            <LoadMore show={showLoading} id={LOAD_MORE_ID} />
          </WingBlank>
        )}
      </div>
    </div>
  );
};

export default Search;
